//
//  SepWebVC.swift
//  ANOA
//
//  Created by 邱仙凯 on 2024/9/28.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit
import WebKit

class SepWebVC: UIViewController, WKNavigationDelegate, WKUIDelegate,operatable,refreshable {
    
    var commonWebview = WKWebView()
    var reportUrl:String? // 网页路径
    var pathUrl:String? // 本地路径
    var htmlStr: String?
    /// 是否需要自动编码
    var needEncode = true
    var adjustWebContent: UIEdgeInsets = .zero
    var closeMiniFont = false
    fileprivate lazy var progress: UIProgressView = {
        let progress = UIProgressView()
        progress.frame = CGRect(x: 0, y: 0, width: KSGlobal.screenW, height: 5)
        progress.backgroundColor = #colorLiteral(red: 0.1803921569, green: 0.1960784314, blue: 0.568627451, alpha: 1)
        return progress
    }()
    var isTranslucent_ori:Bool? // 本控件需要操作，但是又不希望影响到其他的控件
    init(needEncode:Bool = true) {
        self.needEncode = needEncode
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
       
        // 防止位置会下移一个导航的高度
        isTranslucent_ori = self.navigationController?.navigationBar.isTranslucent
        self.navigationController?.navigationBar.isTranslucent = false
        
        
        let appdelegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
        appdelegate.allowRotation = true
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let trat = isTranslucent_ori {
            self.navigationController?.navigationBar.isTranslucent = trat
        }
   
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.allowRotation = false //禁止旋转
        UIDevice.current.setValue(1, forKey: "orientation")
        /*KVC的方式设置物理转动的值，用于强制旋转，也就是手机传感器没有检测到手机转动，但给其系统状态赋值成已经是竖屏的状态。
        */
         UIViewController.attemptRotationToDeviceOrientation() //应用刷新视图
        
    }
    lazy var btn:UIButton = {
        let v = UIButton()
        v.layer.cornerRadius = 8
        v.layer.borderWidth = 1
        v.layer.borderColor = Theme.primaryColor().cgColor
        v.setTitleColor(Theme.primaryColor(), for: .normal)
        v.setTitle("保存", for: .normal)
        return v
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
 
        
        self.view.backgroundColor = .white
        
        let config = WKWebViewConfiguration()
        config.preferences = WKPreferences()
        if #available(iOS 14, *) {
            config.defaultWebpagePreferences.allowsContentJavaScript = true
        } else {
            config.preferences.javaScriptEnabled = true
        }
        
        if !closeMiniFont {
            config.preferences.minimumFontSize = 18
        }
//        config.applicationNameForUserAgent = "\(config.applicationNameForUserAgent ?? "iOS unknown")?token=\(TOKEN)&url=\(HTTPStr)"

        config.processPool = WKProcessPool()
        let navH = self.navigationController.isSome ? self.navigationController!.navigationBar.frame.height : 0
        let topH = ksStatusbarHeight + navH
        
        
        
         
        
        // 创建WKUserContentController实例，用于与JavaScript进行通讯
        let contentController = WKUserContentController()
        
        // 注册消息处理器，监听JavaScript中的消息
        contentController.add(self, name: "downloadHandler")
        contentController.add(self, name: "callbackHandler")
        contentController.add(self, name: "rebackLogin")
      

        // 配置WebView使用contentController
        config.userContentController = contentController
        
        
        
        commonWebview = WKWebView(frame: CGRect(x: 0, y:0 , width: KSGlobal.screenW, height: KSGlobal.screenH - topH), configuration: config)
        commonWebview.customUserAgent = "\(config.applicationNameForUserAgent ?? "iOS unknown")?token=\(TOKEN)&url=\(HTTPStr)"
        if adjustWebContent != .zero {
            commonWebview.scrollView.contentInset = adjustWebContent
        }
         view.addSubview(commonWebview)
        // 用约束能更好的适配旋转屏
        commonWebview.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(self.view)
            make.bottom.equalTo(self.view).offset(-55)

        }
        //进度条
        commonWebview.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        //添加webView
        commonWebview.navigationDelegate = self
        commonWebview.uiDelegate = self
        
        commonWebview.addSubview(progress)
        startShowContent()
     

        if self.excuteType != .view {
            self.addBtn()
        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(viewDidLoadAndAfterLogin), name: NSNotification.Name(rawValue: UPDATE_NOTIFICATION), object: nil)
        
    }
    
    @objc private func viewDidLoadAndAfterLogin() {
        self.commonWebview.customUserAgent = "token=\(TOKEN)&url=\(HTTPStr)"
        self.commonWebview.reload()
    }
    
    func addBtn() {
        
        let v = UIView()
        v.backgroundColor = .white
        view.addSubview(v)
        v.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(55)
        }
         
        v.addSubview(btn)
        btn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(5)
            make.width.equalTo(100)
            make.height.equalTo(35)
            make.centerX.equalToSuperview()
      }
        btn.addTouchUpInSideAction { _ in
            self.commonWebview.evaluateJavaScript("saveSourceFormMobileClick()", completionHandler: { (result, error) in
                if let error = error {
                    print("Error: \(error.localizedDescription)")
                } else if let result = result {
                    print("Result: \(result)")
                }
            })
        }
        
    
        
    }
    
    
    func startShowContent() {
        
        if let webStr = htmlStr {
            commonWebview.loadHTMLString(webStr, baseURL: nil)
        }
        
        if let urlstr = reportUrl {
            var dealStr:String = ""
            if  self.needEncode {
                dealStr = urlstr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
            } else {
                dealStr = urlstr
            }
            if let url = URL(string: dealStr) {
                // 不缓存
                commonWebview.load(URLRequest(url: url,cachePolicy: .reloadIgnoringLocalCacheData))
            } else {
                KSToast("url有误")
                self.navigationController?.popViewController(animated: true)
            }
        }
        
        if let pUrl = pathUrl {
            let url = URL(fileURLWithPath: pUrl)
            commonWebview.load(URLRequest(url: url))
        }
    }
    
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            print("进度")
            print(commonWebview.estimatedProgress)
            progress.progress = Float(commonWebview.estimatedProgress)
        }
        
        if !commonWebview.isLoading {
            UIView.animate(withDuration: 0.55, animations: { () -> Void in
                self.progress.alpha = 0.0;
            })
        }
        
    }
    
    
    
    
    deinit {
        print("网页显示销毁")
        
        NotificationCenter.default.removeObserver(self)
        commonWebview.configuration.userContentController.removeAllUserScripts()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
}

// MARK: navigationDelegate
extension SepWebVC:WKScriptMessageHandler {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        
        
        
        UIView.animate(withDuration: 0.55, animations: { () -> Void in
            self.progress.alpha = 0.0;
        })
        
        
        
        
        let saveCode = """
        function saveSuccess() {
            window.webkit.messageHandlers.callbackHandler.postMessage("handle save Func!");
        }
        """
        
        
        
        // 直接注入 JavaScript 代码
        let fileCode = """
              (function() {
                  // 保存原始的 downLoadMobilePreview 函数（如果存在）
                  if (typeof window.downLoadMobilePreview === "function") {
                      window.originalDownLoadMobilePreview = window.downLoadMobilePreview;
                  }
                  // 重写 downLoadMobilePreview 函数
                  window.downLoadMobilePreview = function(url,fileName) {
                      // 使用 postMessage 将消息发送回 Swift
                      if (window.webkit && window.webkit.messageHandlers.downloadHandler) {
                          window.webkit.messageHandlers.downloadHandler.postMessage({ url: url,fileName:fileName });
                      }
                      // 如果需要，可以调用原始的 downLoadMobilePreview 函数（如果存在）
                        var originalFunction = window.originalDownLoadMobilePreview;
                        if (originalFunction) {
                            originalFunction(url);
                        }
                  };
              })();
              """
        
        
        
        
        webView.evaluateJavaScript(saveCode) { (result, error) in
            if let error = error {
                print("Error injecting JS: \(error)")
            } else {
                print("save code injected successfully.")
            }
        }
        webView.evaluateJavaScript(fileCode) { (result, error) in
            if let error = error {
                print("Error injecting JS: \(error)")
            } else {
                print("fileCode code injected successfully.")
            }
        }
        //通过走mobileOpenHtmlErrorClick方法来试探一下是不是超时，该重新登录
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
            
            self.commonWebview.evaluateJavaScript("mobileOpenHtmlErrorClick()", completionHandler: { (result, error) in
                if let error = error {
                    print("Error: \(error.localizedDescription)，没有超时")
                } else {
                    KSToast("登录超时，重新登录")
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.8) {
                        // 没有error 执行成功了，真的需要重新登录了
                        LifeCycleTool.shared.logout()
                    }
                }
            })
        }
    }
    // 接收JavaScript发送的消息
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        if message.name == "callbackHandler", let messageBody = message.body as? String {
            print("JavaScript sent a message: \(messageBody)")
            // 处理JavaScript消息
            KSToast("保存成功")
            if let clo = self.refreshClosure {
                clo()
            }
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                self.navigationController?.popViewController(animated: true)
            }
        }
   
        if message.name == "downloadHandler", let args = message.body as? [String: Any] {
            
            let urlString = args["url"] as? String
            let titleString = args["fileName"] as? String
            
            KSLog("相应---")
            KSLog(titleString)
            KSLog(urlString)
            
            let cwebV = CommonWebController()
            cwebV.reportUrl = urlString
            cwebV.title = titleString
            self.navigationController?.pushViewController(cwebV, animated: true)
            
            
        }
        
        if message.name == "rebackLogin" {
            sessionInvalid(times: 0) {
                self.viewDidLoadAndAfterLogin()
            }
        }
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("加载出了点问题")
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("start")
    }
}


